<?php defined('BASEPATH') OR exit('No direct script access allowed');


class Wallpaper_model extends WS_model
{
    public function insert($data)
    {
        $this->db->insert('wallpapers', $data);
        $insert_id = $this->db->insert_id();
        $this->insert_path_single($insert_id, $data['category_seq_id']);
        return $insert_id;
    }

    public function insert_path_single($insert_id, $category_id)
    {
        return $this->insert_path_single_($insert_id, $category_id);
    }

    public function removeWallpaperPath($wall_id)
    {
        return $this->removeWallpaperPath_($wall_id);
    }

    public function insertTags($data, $batch = false)
    {
        if ($batch)
            $this->db->insert_batch('wallpapers_tags', $data);
        else
            $this->db->insert('wallpapers_tags', $data);
        return $this->db->insert_id();
    }

    public function insert_colors($data, $batch = false)
    {
        if ($batch)
            $this->db->insert_batch('wallpapers_colors', $data);
        else
            $this->db->insert('wallpapers_colors', $data);
        return $this->db->insert_id();
    }

    public function update($data, $where, $key = false)
    {
        if ($key) {
            $this->db->update_batch('wallpapers', $data, $key);
        } else {
            $this->db->update('wallpapers', $data, $where);
        }
        return $this->db->affected_rows();
    }

    public function deleteWallColors($id)
    {
        $this->db->where_in('wallpaper_seq_id', $id);
        $this->db->delete('wallpapers_colors');
        return $this->db->affected_rows();
    }

    public function deleteWallTags($id)
    {
        $this->db->where_in('wallpaper_seq_id', $id);
        $this->db->delete('wallpapers_tags');
        return $this->db->affected_rows();
    }

    public function deleteWallPath($id)
    {
        $this->db->where_in('wallpaper_seq_id', $id);
        $this->db->delete('wallpapers_path');
        return $this->db->affected_rows();
    }

    public function deleteWallDownloads($id)
    {
        $this->db->where_in('wd_wid', $id);
        $this->db->delete('wallpapers_downloads');
        return $this->db->affected_rows();
    }

    public function deleteWallFavourites($id)
    {
        $this->db->where_in('wf_wid', $id);
        $this->db->delete('wallpapers_favourites');
        return $this->db->affected_rows();
    }

    public function deleteWallViews($id)
    {
        $this->db->where_in('wv_wid', $id);
        $this->db->delete('wallpapers_views');
        return $this->db->affected_rows();
    }

    public function deleteWallVotes($id)
    {
        $this->db->where_in('vote_wid', $id);
        $this->db->delete('wallpapers_votes');
        return $this->db->affected_rows();
    }

    public function deleteWallComment($id)
    {
        $this->db->select('wc.comment_seq_id')
            ->from('wallpapers_comments wc')
            ->where_in('wc.wallpaper_seq_id', $id);
        $sql = $this->sql();

        $this->db->where_in("comment_seq_id = ($sql)", false, false)
            ->delete('comments_reports');

        $this->db->where_in('wallpaper_seq_id', $id)
            ->delete('wallpapers_comments');
        return $this->db->affected_rows();
    }

    public function deleteByIDs($ids)
    {
        if (!is_array($ids))
            $ids = array($ids);
        $this->db->where_in('wallpaper_seq_id', $ids);
        $this->db->delete('wallpapers');

        $affected = $this->db->affected_rows();

        $this->deleteWallColors($ids);
        $this->deleteWallTags($ids);
        $this->deleteWallPath($ids);
        $this->deleteWallDownloads($ids);
        $this->deleteWallFavourites($ids);
        $this->deleteWallViews($ids);
        $this->deleteWallVotes($ids);
        $this->deleteWallComment($ids);


        return $affected;
    }

    public function get_tags($filter = array())
    {
        $perPage = (isset($filter['per_page']) ? $filter['per_page'] : FALSE);
        $offset = (isset($filter['offset']) ? $filter['offset'] : FALSE);
        $count = (isset($filter['count']) ? $filter['count'] : false);
        $top_count = (isset($filter['top_count']) ? $filter['top_count'] : false);

        $this->db->select('tag_name,count(*) AS count');
        $this->db->from('wallpapers_tags');
        $this->db->group_by('tag_name');

        if ($top_count) {
            $this->db->order_by('count', 'desc');
            $row = $this->row();
            return $row ? $row->count : 0;
        }

        if ($count) {
            $query = $this->db->query("SELECT count(*) as count FROM ({$this->sql(true)}) as t");
            return $query->row()->count;
        }
        if ($perPage)
            $this->db->limit($perPage, $offset);

        $this->db->order_by('count', 'desc');
        return $this->result();
    }

    public function getWallpapers($filter = array())
    {
        $count = (isset($filter['count']) ? true : false);
        $perPage = (isset($filter['per_page']) ? $filter['per_page'] : FALSE);
        $offset = (isset($filter['offset']) ? $filter['offset'] : FALSE);
        $name = (isset($filter['name']) ? $filter['name'] : FALSE);
        $category = (isset($filter['category']) ? $filter['category'] : FALSE);
        $byPath = (isset($filter['bypath']) ? $filter['bypath'] : TRUE);
        $keyword_related = (isset($filter['keyword_related']) ? $filter['keyword_related'] : false);
        $colors = (!empty($filter['colors']) ? $filter['colors'] : false);
        $sizes = (!empty($filter['size']) ? $filter['size'] : false);
        $rss = (isset($filter['rss']) ? $filter['rss'] : false);
        $tag = (isset($filter['tag']) ? $filter['tag'] : false);
        $by_user_favourites = (isset($filter['by_user_favourites']) ? $filter['by_user_favourites'] : false);
        $by_user_likes = (isset($filter['by_user_likes']) ? $filter['by_user_likes'] : false);
        $by_user_dislikes = (isset($filter['by_user_dislikes']) ? $filter['by_user_dislikes'] : false);
        $by_user_downloads = (isset($filter['by_user_downloads']) ? $filter['by_user_downloads'] : false);
        $show_disabled = (isset($filter['show_disabled']) ? $filter['show_disabled'] : false);
        $options['count'] = $count;


        if ($count && isset($filter['sort']) && $filter['sort'] == 'random') {
            return false;
        }

        if (isset($filter['cacheoff']))
            $this->cacheOff();

        $type = ($byPath ? 'bypath' : '');
        if ($colors)
            $type = 'color';

        if ($tag)
            $type = 'tag';

        if ($by_user_favourites) {
            $type = 'by_user_favourites';
            $options['by_user_favourites'] = $by_user_favourites;
        }
        if ($by_user_likes) {
            $type = 'by_user_likes';
            $options['by_user_likes'] = $by_user_likes;
        }
        if ($by_user_dislikes) {
            $type = 'by_user_dislikes';
            $options['by_user_dislikes'] = $by_user_dislikes;
        }
        if ($by_user_downloads) {
            $type = 'by_user_downloads';
            $options['by_user_downloads'] = $by_user_downloads;
        }

        if (!$type)
            $type = 'normal';


        $options['tag'] = $tag;
        $options['colors'] = $colors;


        $this->wallpaperTemplate(true, $type, $options);

        if ($name || $keyword_related) {
            $this->load->helper("inflector");
        }

        if ($name) {
            $singular = singular($name);
            $plural = plural($singular);
            $saxon_genitive = $singular . "\\'s " . $plural . "\\'";
            $matchKeyword = $singular . ' ' . $plural . ' ' . $saxon_genitive;

            $noSpace_keyword = str_replace(' ', '', $name);
            $explode_keyword = explode(' ', $name);
            $s = '';
            foreach ($explode_keyword as $i => $k) {
                if ($i > 0)
                    $s .= ' and ';
                $s .= ' wallpaper_name LIKE "%' . $k . '%" ';
            }
            $sql = "(
                    wallpaper_name LIKE '%{$name}%'
                    OR REPLACE (wallpaper_name, ' ', '') LIKE '%{$noSpace_keyword}%'
                    OR wallpaper_slug LIKE '%{$name}%'
                    OR REPLACE (wallpaper_slug, ' ', '') LIKE '%{$name}%'
                    OR wallpaper_hash LIKE '%{$name}%'
                    OR REPLACE (wallpaper_hash, ' ', '') LIKE '%{$noSpace_keyword}%'
                    OR MATCH (wallpaper_name) AGAINST (
                        '{$matchKeyword}' IN BOOLEAN MODE
                    )
                    or ($s)
                )";
            $this->db->where($sql, false, false);
        }

        if ($category) {
            $this->db->where('c.category_seq_id', $category);
        }

        if (isset($filter['wallpaper_id_not']))
            $this->db->where_not_in('w.wallpaper_seq_id', $filter['wallpaper_id_not']);

        if (!$show_disabled) {
            $this->db->where('w.wallpaper_status', 1);
            $this->db->where('w.wallpaper_approved', 1);
        }

        $this->global_wallpaper();

        if (isset($sizes['width']) && $sizes['width'] && isset($sizes['width']) && $sizes['width']) {
            $this->db->where('w.wallpaper_width >=', $sizes['width']);
            $this->db->where('w.wallpaper_height >=', $sizes['height']);
        }

        if (isset($filter['featured'])) {
            $this->db->where('w.wallpaper_featured', $filter['featured']);
        }

        if (isset($filter['time'])) {
            switch (isset($filter['time']) ? $filter['time'] : '') {
                case 'today':
                    $this->db->where('DATE(wallpaper_date_created)', date('Y-m-d'));
                    break;
                case '7days':
                    $this->db->where('wallpaper_date_created BETWEEN DATE_SUB("' . date('Y-m-d') . '", INTERVAL 7 DAY) and "' . date('Y-m-d') . '"');
                    break;
                case '30days':
                    $this->db->where('wallpaper_date_created BETWEEN DATE_SUB("' . date('Y-m-d') . '", INTERVAL 30 DAY) and "' . date('Y-m-d') . '"');
                    break;
                case '60days':
                    $this->db->where('wallpaper_date_created BETWEEN DATE_SUB("' . date('Y-m-d') . '", INTERVAL 60 DAY) and "' . date('Y-m-d') . '"');
                    break;
            }
        }

        if (isset($filter['where_user_id']))
            $this->db->where('w.user_seq_id', $filter['where_user_id']);

        if ($count)
            return $this->count();

        if ($perPage)
            $this->db->limit($perPage, $offset);

        if ($keyword_related) {
            $singular = singular($keyword_related);
            $plural = plural($singular);
            $saxon_genitive = $singular . "\\'s " . $plural . "\\'";
            $matchKeyword = $singular . ' ' . $plural . ' ' . $saxon_genitive;
            $order_sql = "CASE WHEN MATCH (wallpaper_name) AGAINST ('{$matchKeyword}' IN BOOLEAN MODE) THEN 2 WHEN wallpaper_hash LIKE '%{$keyword_related}%' THEN 1 ELSE 0 END";
            $this->db->order_by($order_sql, 'desc');
        } else {
            switch (isset($filter['sort']) ? $filter['sort'] : '') {
                case 'latest':
                    $this->db->order_by('w.wallpaper_seq_id', 'desc');
                    break;
                case 'downloads':
                    $this->db->order_by('d.total_downloads', 'desc');
                    break;
                case 'latest_asc':
                    $this->db->order_by('w.wallpaper_seq_id', 'asc');
                    break;
                case 'views':
                    $this->db->order_by('v.total_views', 'desc');
                    break;
                case 'favourites':
                    $this->db->order_by('f.total_favourites', 'desc');
                    break;
                case 'rating':
                    $this->db->order_by('vo.vote_up', 'desc');
                    break;
                case 'colors':
                    $this->db->order_by('color_sum', 'desc');
                    break;
                case 'random':
                    $this->cacheOff();
                    $this->db->order_by('w.wallpaper_seq_id', 'RANDOM');
                    if ($perPage)
                        $this->db->limit($perPage);
                    $this->db->offset('0');
                    break;
                default:
                    $this->db->order_by('w.wallpaper_seq_id', 'desc');
                    break;
            }
        }

        if ($rss) {
            $this->db->limit($this->config->item('rss_limit') ? $this->config->item('rss_limit') : 10, false);
            $this->db->offset('0');
            return $this->result();
        }

        return $this->result();
    }

    public function getWallpaperByID($id)
    {
        $this->wallpaperTemplate();
        $this->db->where('w.wallpaper_seq_id', $id);
        return $this->row();
    }

    public function getWallpaperByHASH($hash)
    {
        $this->wallpaperTemplate();
        $this->db->where('w.wallpaper_hash', $hash);
        return $this->row();
    }

    public function removeWallpaperTags($wall_ID)
    {
        $this->db->delete('wallpapers_tags', array('wallpaper_seq_id' => $wall_ID));
        return $this->db->affected_rows();
    }

    public function get_wallpaper($filter = array())
    {
        $this->wallpaperTemplate(true);
        if (isset($filter['category_slug']))
            $this->db->where('cFullSlug', $filter['category_slug']);
        if (isset($filter['wallpaper_slug']))
            $this->db->where('wallpaper_slug', $filter['wallpaper_slug']);
        if (isset($filter['wallpaper_hash']))
            $this->db->where('wallpaper_hash', $filter['wallpaper_hash']);
        if (isset($filter['user_seq_id']))
            $this->db->where('w.user_seq_id', $filter['user_seq_id']);
        if (isset($filter['cache_off']))
            $this->cacheOff();
        if (isset($filter['md5']))
            return $this->sql_md5();
        return $this->row();
    }

    public function get_wallpaper_voteStats($wid)
    {
        $this->cacheOff();
        $this->db->select('sum(vote_up) AS vote_up,sum(vote_down) AS vote_down,vote_wid');
        $this->db->from('wallpapers_votes');
        $this->db->group_by('vote_wid');
        $this->db->where('vote_wid', $wid);
        return $this->row();
    }

    public function previousNext($wallpaper_id, $width = false, $height = false)
    {
        $cat_template = $this->wallCatTemplate();
        $this->db->select("w.*,c.*,'previous' as type");
        $this->db->from('wallpapers w');
        $this->db->join("({$cat_template}) as c", 'c.category_seq_id = w.category_seq_id', 'left');
        $this->db->where('w.wallpaper_seq_id > ' . $wallpaper_id);
        $this->db->where('w.wallpaper_status = 1');
        if ($width && $height) {
            $this->db->where('w.wallpaper_width >=', $width);
            $this->db->where('w.wallpaper_height >=', $height);
        }
        $this->db->order_by('w.wallpaper_seq_id', 'ASC');
        $this->db->limit(1);
        $prev_sql = $this->sql(true);

        $this->db->select("w.*,c.*,'next' as type");
        $this->db->from('wallpapers w');
        $this->db->join("({$cat_template}) as c", 'c.category_seq_id = w.category_seq_id', 'left');
        $this->db->where('w.wallpaper_seq_id < ' . $wallpaper_id);
        $this->db->where('w.wallpaper_status = 1');
        if ($width && $height) {
            $this->db->where('w.wallpaper_width >=', $width);
            $this->db->where('w.wallpaper_height >=', $height);
        }
        $this->db->order_by('w.wallpaper_seq_id', 'DESC');
        $this->db->limit(1);
        $this->eachDay_newCache();
        $next_sql = $this->sql(true);

        $query = $this->db->query("($prev_sql)UNION ALL($next_sql)");
        if ($query->num_rows()) {
            $return = array();
            foreach ($query->result() as $res) {
                $return[$res->type] = $res;
            }
            return $return;
        }
        return false;
    }

    public function is_viewed($data)
    {
        $this->cacheOff();
        foreach ($data as $k => $v)
            $this->db->where($k, $v);
        $this->db->from('wallpapers_views');
        return $this->row();
    }

    public function insert_view($data)
    {
        $this->db->insert('wallpapers_views', $data);
        return $this->db->insert_id();
    }

    public function insert_download($data)
    {
        $this->db->insert('wallpapers_downloads', $data);
        return $this->db->insert_id();
    }

    public function is_Wallpaper_ratedBYUser($wid, $uid)
    {
        $this->cacheOff();
        $this->db->from('wallpapers_votes wv');
        $this->db->where('wv.vote_uid', $uid);
        $this->db->where('wv.vote_wid', $wid);
        return $this->row();
    }

    public function is_userAddedToFavourite($wid, $uid)
    {
        $this->cacheOff();
        $this->db->from('wallpapers_favourites wf');
        $this->db->where('wf.wf_uid', $uid);
        $this->db->where('wf.wf_wid', $wid);
        return $this->row();
    }

    public function get_colors($wid)
    {
        $this->db->from('wallpapers_colors');
        $this->db->where('wallpaper_seq_id', $wid);
        return $this->result();
    }

    public function get_comments($filter)
    {
        $this->cacheOff();
        $this->db->select('wc.*,u.*');
        $this->db->from('wallpapers_comments wc');
        $this->db->join('wallpapers w', 'w.wallpaper_seq_id = wc.wallpaper_seq_id');
        $this->db->join('user u', 'u.user_seq_id = wc.user_seq_id', 'left');
        $this->db->where('w.wallpaper_hash', $filter['wallpaper_hash']);
        $this->db->where('wc.comment_status', 1);

        if (isset($filter['count']))
            return $this->count();

        $this->db->limit($filter['per_page'], $filter['offset']);
        $this->db->order_by('wc.comment_seq_id', 'desc');
        return $this->result();
    }

    public function insert_comment($data)
    {
        $this->db->insert('wallpapers_comments', $data);
        return $this->db->insert_id();
    }

    public function get_single_commentBYID($id)
    {
        $this->cacheOff();
        $this->db->select('wc.*,u.*');
        $this->db->from('wallpapers_comments wc');
        $this->db->join('wallpapers w', 'w.wallpaper_seq_id = wc.wallpaper_seq_id');
        $this->db->join('user u', 'u.user_seq_id = wc.user_seq_id', 'left');
        $this->db->where('wc.comment_seq_id', $id);
        return $this->row();
    }
}